package com.zh.risk.aop;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zh.common.entity.JSONResult;
import com.zh.common.entity.TransIntercept;

import com.zh.common.exception.MyControllerException;
import com.zh.common.exception.MyServiceException;
import com.zh.risk.entity.CheckResult;
import io.swagger.annotations.ApiOperation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @version 1.0
 * @Description : 交易风控切面 controller层
 * @Author : chenfei
 * @Create in : 2020/10/14 17:05
 */
@Aspect
@Component
public class TransInterceptAop {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final Logger log = LoggerFactory.getLogger(TransInterceptAop.class);


    @Pointcut("execution(* com.zh.risk.controller.CallRiskController.transIntercept(..))")
    public void modRecordAopLog() { }

    private Long date = null;
    @Async
    @Before(value = "modRecordAopLog()")
    public void BeforeMod(@NotNull JoinPoint jp) {
        //设置请求时间
        date  = new Date().getTime();
    }


    @Async
    @AfterReturning(returning="result", value = "modRecordAopLog()")
    public void After(@NotNull  JoinPoint jp, JSONResult<Object> result) {
        // 获取方法信息
        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        Method method = methodSignature.getMethod();
        Long resultDate =new Date().getTime();
        try {
            ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);

            JSONObject param = JSON.parseObject(String.valueOf(GetRequestParams.getRequestParamsByJoinPoint(jp).get("param")));
            TransIntercept transIntercept = new TransIntercept();
            transIntercept.setMethod(method.getName());
            transIntercept.setNotes(apiOperation.notes());
            transIntercept.setMerchno(param.get("merchno").toString());
            transIntercept.setTraceno(param.get("traceno").toString());
            transIntercept.setAmount(Double.valueOf(param.get("amount").toString()));
            transIntercept.setStrategyId(param.get("strategyId").toString());
            transIntercept.setIdentityId(param.get("identityId").toString());
            transIntercept.setRequestResult(result.getCode().toString());
            if(result.getData()!=null){//请求成功
                CheckResult checkResult = (CheckResult) result.getData();
                transIntercept.setResult(checkResult.getFlag());
                transIntercept.setResponse(checkResult.getMessage());
                transIntercept.setRole(result.getMessage());//添加触发的风控规则
                transIntercept.setLevelType(5);
            }else{//请求成功，缺少参数之类的
                transIntercept.setResult(false);
                transIntercept.setResponse(result.getMessage());
                transIntercept.setLevelType(3);
            }

            transIntercept.setResponseDate( (resultDate-date) +"ms" );
            transIntercept.setCreateDate(DateUtil.now());
            mongoTemplate.insert(transIntercept);
        } catch (Exception e) {
           // log.error("异常信息:{}", e.getLocalizedMessage());
        }
    }

//    @Async
//    @AfterThrowing(value = "modRecordAopLog()", throwing = "ex")
//    public void afterThrowing(JoinPoint point,Throwable ex) {
//        // 获取方法信息
//        MethodSignature methodSignature = (MethodSignature) point.getSignature();
//        Method method = methodSignature.getMethod();
//        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
//        Object param =  point.getArgs()[0];
//        log.error("请求方法名称:{},请求方法:{},请求参数:{}", apiOperation.notes(),apiOperation.tags()[0],param);
//        if (ex instanceof MyControllerException || ex instanceof MyServiceException){//自定义异常
//            log.error("自定义异常：" + ex);
//        }else{
//            log.error("系统异常：" + ex);
//        }
//    }



}
